import java.sql.*;
import java.io.*;

public
class DatabaseTest
{
	public static DatabaseTest databaseTest;
	protected Connection connection = null;
	protected static PrintWriter outp = null;
	
	public DatabaseTest(String fileName)
	{
		connect("test");
		writeRecords(fileName);
		close();
	}
	public static void setOutput()
	{
		try{
	outp = new PrintWriter(new OutputStreamWriter(System.out, "Cp852"), true);
		}
		catch(UnsupportedEncodingException e){
			System.out.println("Nie mona ustawi strony kodowej Cp852.");
			outp = new PrintWriter(new OutputStreamWriter(System.out), true);
		}
	}
	public static void main(String args[])
	{
		setOutput();
		if (args.length < 1){
			outp.println("Wywoanie programu: 'DatabaseTest nazwa_pliku'");
			System.exit(0);
		}
		databaseTest = new DatabaseTest(args[0]);
	}
	public void connect(String databaseName)
	{
		try{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		}
		catch(ClassNotFoundException e){
			outp.println("Bd przy adowaniu sterownika bazy: " + e);
			System.exit(-1);
		}
		try{
		connection = DriverManager.getConnection("jdbc:odbc:" + databaseName);
		}
		catch(SQLException e){
			outp.println("Nie mona nawiza poczenia z baz: " + e);
			System.exit(-1);
		}
		outp.println("\nPoczenie nawizane!\n");
	}
	public void close()
	{
		try{
			connection.close();
		}
		catch(SQLException e){
			outp.println("Bd przy zamykaniu poczenia: " + e);
			System.exit(-1);
		}
		outp.println("\nPoczenie zamknite!\n");
	}
	public void writeRecords(String fileName)
	{
		PrintWriter fileStream = null;
		try{
		fileStream = new PrintWriter (new FileOutputStream(fileName), true);
		}
		catch(FileNotFoundException e){
			outp.println("Nie moge utworzy pliku: " + fileName);
			System.exit(-1);
		}
		String query = "SELECT * FROM OSOBA";
		try{
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery(query);
			while(rs.next()){
				String imie = rs.getString("IMIE");
				String nazwisko = rs.getString("NAZWISKO");
				String adres = rs.getString("ADRES");
				String telefon = rs. getString("TELEFON");
				String email = rs.getString("EMAIL");
				fileStream.println(
					imie + " " + 
					nazwisko + " " + 
					adres + " " + 
					telefon + " " +
					email);
			}
		}
		catch(SQLException e){
			outp.println("Bd podczas przetwarzania danych: " + e);
		}
		catch(Exception e){
			outp.println("Bd oglny: " + e);
		}
	}
}
